package com.demo.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;

import com.demo.bean.User;
import com.demo.service.AppService;
import com.demo.util.HTML;

/**
 * 
 */

/**
 * @author Issac
 *
 */
@Controller
@RequestMapping("/app")
public class AppController implements ServletContextAware {
	
	@Autowired
	private AppService appService;
	
	public AppService getAppService() {
		return appService;
	}
	
	public void setAppService(AppService appService) {
		this.appService = appService;
	}
	
	private ServletContext servletContext; 
	public void setServletContext(ServletContext context) {
		this.servletContext = context;
	}


	@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
	
	@RequestMapping(value="/add", method = RequestMethod.POST)
	public ModelAndView add(User user){
		int code = appService.add(user);
		
		return new ModelAndView("appSuccess", "user", user);
	}
	
	@ResponseBody
	@RequestMapping(value="/login/{user}", method=RequestMethod.GET)
	public Map<String, Object> login(@PathVariable String user){
		Map<String, Object> map = new HashMap<String, Object>();
		User us = appService.get(user);
		map.put("user", "123456");
		return map;
	}
	
	@ResponseBody
	@RequestMapping(value = "/show", method=RequestMethod.GET)
	public Map<String, Object> show(ModelMap model, @RequestParam("user") String user){
		model.addAttribute("user", user);
		return model;
	}
	
	@ResponseBody
	@RequestMapping(value = "/generate", method=RequestMethod.GET)
	public Map<String, Object> generate(){
		Map<String, Object> map = new HashMap<String, Object>();
		List<User> userList = appService.list();
		map.put("user", userList);
		HTML.createIndex(servletContext, map);
		return map;
	}
	
}
